package com.example.l3.ktm.DownloadUtility;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;

@SuppressLint("DefaultLocale")
public class AsyncFileLoader extends AsyncTask<Void, Void, Boolean> {
	
	private final String TAG = "L3";
	
	private String _urlStr;
	
	private URL _url;
	private URLConnection _urlConnection;
	
	private final int TIMEOUT_READ = 5000;
	private final int TIMEOUT_CONNECT = 30000;

	private InputStream _inputStream;
	private BufferedInputStream _bufferedInputStream;

	private FileOutputStream _fileOutputStream;
	private File _outputFile;
	
	private byte[] buff = new byte[5 * 1024];
	
	private int _totalByte = 0;
	private int _currentByte = 0;

	public AsyncFileLoader(String urlStr, File outputFile){		
		this._urlStr = urlStr;		
		this._outputFile = outputFile;
	}

	
	@Override
	protected Boolean doInBackground(Void... arg0) {
		// TODO Auto-generated method stub
	
		try {
			connect();
		} catch (Exception e) {
			Log.d(TAG, "error on preExecute:" + e.toString());
			cancel(true);
		}
		
		if (isCancelled()) {
			return false;			
		}
		
		try {
			int len;
			while ( (len = _bufferedInputStream.read(buff)) != -1) {
				_fileOutputStream.write(buff, 0, len);
				_currentByte += len;
				
				if (isCancelled()) {
					break;
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.d(TAG, "error on read file:" + e.toString());
		}
		
		
		return true;
	}
	
	@Override
	protected void onPreExecute() {		
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		
		if (result == true) {
			try {
				close();
			} catch (Exception e) {
				Log.d(TAG, "error on postExecute:" + e.toString());				
			}
		}else{
			Log.d(TAG, "result: load error");
		}
		
	}
	
	private void close() throws IOException {
		_fileOutputStream.flush();
		_fileOutputStream.close();
		_bufferedInputStream.close();

	}


	private void connect() throws IOException {
		_url = new URL(_urlStr);
		
		_urlConnection = _url.openConnection();
		_urlConnection.setReadTimeout(TIMEOUT_READ);
		_urlConnection.setConnectTimeout(TIMEOUT_CONNECT);
		
		_inputStream = _urlConnection.getInputStream();
		_bufferedInputStream = new BufferedInputStream(_inputStream, 1024 * 5);
		_fileOutputStream = new FileOutputStream(_outputFile);
		 
		//_totalByte = _bufferedInputStream.available(); //this is not work
		_totalByte = _urlConnection.getContentLength();
		_currentByte = 0;

	}
	
	public int getLoadedBytePercent()
	{
		if(_totalByte <= 0){
			return 0;
		}
		//Log.d(TAG, Integer.toString(_currentByte) + ":" + Integer.toString(_totalByte));
		return (int)Math.floor(100 * _currentByte/_totalByte);
	}
	
	public String getProgressDownload()
	{
		String progressDownload = "";
		
		if(_totalByte <= 0){
			return "0/0 Bytes";
		}
		
		float bytedownloaded = 0.f;
		float byteTotal = 0.f;
		
		if (_totalByte > 1024 * 1024) { // file size > 1 MB
			bytedownloaded = _currentByte *1.f / 1024 / 1024;
			byteTotal = _totalByte *1.f / 1024 / 1024;
			
			progressDownload = String.format("Progress: %.1f / %.1f MB", bytedownloaded,byteTotal);
		} else {
			bytedownloaded = _currentByte *1.f / 1024;
			byteTotal = _totalByte *1.f / 1024;
			progressDownload = String.format("Progress: %.1f / %.1f KB", bytedownloaded,byteTotal);
		}
		
		return progressDownload;
	}

	
}
